package com.dwx.guli.service.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dwx.guli.service.edu.entity.Subject;
import com.dwx.guli.service.edu.entity.excel.ExcelSubjectData;
import com.dwx.guli.service.edu.mapper.SubjectMapper;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
public class ExcelSubjectDataListener extends AnalysisEventListener<ExcelSubjectData> {
    private SubjectMapper subjectMapper;

    @Override
    public void invoke(ExcelSubjectData data, AnalysisContext analysisContext) {
        String levelOneTitle = data.getLevelOneTitle();
        String levelTwoTitle = data.getLevelTwoTitle();
        Subject byTitle = getByTitle(levelOneTitle, "0");
        String parentId=null;
        if(null!=byTitle){
            parentId=byTitle.getId();
        }else {
            byTitle=new Subject();
            byTitle.setTitle(levelOneTitle);
            byTitle.setParentId("0");
            subjectMapper.insert(byTitle);
            parentId=byTitle.getId();
        }
        Subject subByTitle = getByTitle(levelTwoTitle, parentId);
        if(null==subByTitle){
            subByTitle=new Subject();
            subByTitle.setTitle(levelTwoTitle);
            subByTitle.setParentId(parentId);
            subjectMapper.insert(subByTitle);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("所有数据解析完成！");
    }

    private Subject getByTitle(String title,String parentId){
        QueryWrapper<Subject> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("title",title);
        queryWrapper.eq("parent_id",parentId);
        Subject subject = subjectMapper.selectOne(queryWrapper);
        return subject;
    }
}
